package alarm.ruiqi.com.alarm_pro.service;

import android.content.Context;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lidroid.xutils.util.LogUtils;

import alarm.ruiqi.com.alarm_pro.R;
import alarm.ruiqi.com.alarm_pro.domain.JsonPageModel;
import alarm.ruiqi.com.alarm_pro.domain.Tab_Item;
import alarm.ruiqi.com.alarm_pro.utils.Constant;
import alarm.ruiqi.com.alarm_pro.utils.RequestURL;

/**
 * Created by 徐宇健 on 2015/9/1 0001.
 */
public class TabsServiceImpl {
    private Context mContext;
    private int[] mIds;

    public TabsServiceImpl(Context context){
        this.mContext = context;
        mIds = mContext.getResources().getIntArray(R.array.tab_title_id);
    }

    public int[] getIds() {
        return mIds;
    }

    /**
     * 初始化栏目数据
     */
    public void initTabData(){
        //数据放入缓存,key为id
        for (int i = 0; i < mIds.length; i++) {
            String url =    RequestURL.getTabURLById(mIds[i]);
            final int finalI = i;
            Volley.newRequestQueue(mContext).add(new StringRequest(url,
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
                            MobileApplication.cacheUtils.put(Constant.GENERAL_CACHE_TABS + mIds[finalI], response, 60 * 60);
                        }
                    }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    LogUtils.i(error.toString());
                }
            }
            ));
        }
    }

    public  String[] getTab_Urls(){
        Gson gson = new Gson();
        String urls[]= new String[mIds.length];
        for (int i = 0; i <mIds.length; i++) {
            JsonPageModel<Tab_Item>  model =    gson.fromJson(MobileApplication.cacheUtils.getAsString(Constant.GENERAL_CACHE_TABS + mIds[i]), new TypeToken<JsonPageModel<Tab_Item>>() {
            }.getType());
            if (model.getContent().size()>0){
                urls[i]  = model.getContent().get(0).getLink();
            }else {
                urls[i]  = "";
            }
        }
        return  urls;
    }
}
